package com.iot08.admin.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.admin.config.mob.RedisClusterService;
import com.iot08.common.config.redis.RedisService;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.util.ChangeAddress;
import com.iot08.common.response.Response;
import com.iot08.common.response.ResponseEnum;
import com.iot08.common.utils.HttpReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @version 1.0
 * @Description: 通知相关的请求业务
 * @time: 2020/9/5 9:35
 * @author: Rock
 */
@Slf4j
@Service
public class NotifyService {

    @Value("${api.domain: }")
    private String apiDomain;

    @Resource
    private RedisService redisService;

    /**
     * @param imei, operator, isLossDevOption
     * @time: 2020/9/5 9:39
     * @author: Rock
     * @version 1.0
     */
    public JSONObject deviceReset(String imei,  String operator, boolean isLossDevOption, SysUser user) {
        if (StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(imei)) {
            return null;
        }
        JSONObject json = new JSONObject();
        json.put("operator", operator);
        if(user.getType() == Const.CHANNELUSER_TYPE){
            //渠道号 要辨认
            String vender = user.getRole().getChannelCode().toString();
            json.put("vender", operator);
        }else{
            //系统级账号不用 默认 8888
            json.put("vender", "8888");
        }

        json.put("isLossDevOption", isLossDevOption);
        String resJSONStr = HttpReq.sendPostJson(apiDomain + "/getway/reset/" + imei, json.toJSONString());
        if(resJSONStr != null){
            return JSONObject.parseObject(resJSONStr);
        }
        return null;
    }

    /**
     * @param resetImeiList
     * @time: 2021/9/27 18:00
     * @author: weichao
     * @version 1.0
     */
    public JSONObject deviceManyReset(JSONArray resetImeiList, String operator, SysUser user){
        if(resetImeiList==null || resetImeiList.isEmpty()){
            return null;
        }
        JSONObject json = new JSONObject();
        json.put("resetImeiList", resetImeiList);
        json.put("operator", operator);
        if(user.getType() == Const.CHANNELUSER_TYPE){
            //渠道号 要辨认
            String vender = user.getRole().getChannelCode().toString();
            json.put("vender", operator);
        }else{
            //系统级账号不用 默认 8888
            json.put("vender", "8888");
        }
        //http://172.18.114.94:8096/getway/many_reset/
        //http://127.0.0.1:8096/getway/many_reset/
        String URL = apiDomain + "/getway/reset/many_reset";
        long reqTime = System.currentTimeMillis();
        log.info("操作者:{} 进行解绑 {}个设备, URL:{} 开始请求", operator, resetImeiList.size(), URL);
        String resJSONStr = HttpReq.sendPostJson(URL, json.toJSONString());
        reqTime = System.currentTimeMillis() - reqTime;
        log.info("操作者:{} 进行解绑 {}个设备, 请求时间间隔:{} 结果:{}", operator, resetImeiList.size(), reqTime, resJSONStr);
        return JSONObject.parseObject(resJSONStr);
    }

    //主动定位 / 远程关机
    public Response<Object> deviceControl(String imei, Integer operator, SysUser sysUser) {
        if (StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(imei)) {
            return null;
        }
        String accountId = sysUser.getId();
        String account = sysUser.getAccount();
        // 判断是否操作频繁
        String saveKey = String.format("CMSdeviceControl&%s" ,accountId);
        log.info("CMS 操作设备:{}  (0:定位 1:远程关机) operator:{} 操作者:{}({})", imei, operator, account, accountId);
        String redisRes = redisService.get(saveKey);
        if (redisRes != null) {
            return Response.failedResponse("操作频繁");
        }

        JSONObject json = new JSONObject();
        json.put("operator", operator);
        json.put("imei", imei);
        json.put("accountId", accountId);
        json.put("account", account);
        String URL = apiDomain + "/getway/admin/internal/deviceControl";
        String resJSONStr = HttpReq.sendPostJson(URL, json.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(resJSONStr);
        redisService.setex(saveKey, 30, accountId);
        if (jsonObject.getInteger("code") != 0) {
            //失败
            return new Response(jsonObject.get("data"), jsonObject.getInteger("code"), jsonObject.getString("msg"));
        }else{
            return new Response(jsonObject.get("data"), ResponseEnum.STATUS200.getCode(), jsonObject.getString("msg"));
        }
    }

    /**
     * @description 切换IP
     * @author cwj
     * @param [changeAddress, sysUser]
     * @return com.iot08.common.response.Response<java.lang.Object>
     * @date @time 2025/6/13 11:08
     **/
    public Response<Object> changeAddress(ChangeAddress changeAddress,SysUser sysUser) throws IOException {
        if (StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(changeAddress.getImei())) {
            return null;
        }
        String accountId = sysUser.getId();
        // 判断是否操作频繁
        String saveKey = String.format("CMSdeviceChangeIpPort&%s" ,accountId);
        log.info("CMS 操作设备:{} (切换IP) 操作者:{}", changeAddress.getImei(),  accountId);
        String redisRes = redisService.get(saveKey);
        if (redisRes != null) {
            return Response.failedResponse("操作频繁");
        }
        JSONObject json = new JSONObject();
        json.put("imei", changeAddress.getImei());
        json.put("ip",changeAddress.getIp());
        json.put("port",changeAddress.getPort());
        json.put("accountId", accountId);
        String URL = apiDomain + "/getway/admin/internal/changeIpPort";
        String resJSONStr = HttpReq.sendPostJson(URL, json.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(resJSONStr);
        redisService.setex(saveKey, 30, accountId);
        if (jsonObject.getInteger("code") != 0) {
            //失败
            return new Response(jsonObject.get("data"), jsonObject.getInteger("code"), jsonObject.getString("msg"));
        }else{
            //成功
            return new Response(jsonObject.get("data"), ResponseEnum.STATUS200.getCode(), "切换设备"+changeAddress.getImei()+"推送数据地址成功");
        }
    }

    /**
     * @param [openId]
     * @time: 2020/9/5 11:42
     * @author: Rock
     * @version 1.0
     *//*
    public void updateAccountToken(String openId, String type){
        if(StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(openId)){
            return ;
        }
        JSONObject json = new JSONObject();
        json.put("openid", openId);
        json.put("type", type);
        HttpReq.sendPostJson(apiDomain+"/getway/up_account_token", json.toString());
    }

    *//**
     * @param [openId, type]
     * @time: 2020/9/5 11:50
     * @author: Rock
     * @version 1.0
     *//*
    public void sendPushToAccount(String openId, String type, String pushMsg){
        if(StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(openId)){
            return ;
        }
        JSONObject json = new JSONObject();
        json.put("openid", openId);
        json.put("type", type);
        json.put("pushMsg", pushMsg);
        HttpReq.sendPostJson(apiDomain+"/getway/send_push_to_account", json.toString());
    }

    *//**
     * @param [openId, imei]
     * @time: 2020/9/5 12:07
     * @author: Rock
     * @version 1.0
     *//*
    public void deleteRelateDevice(String openId, String imei){
        if(StringUtils.isEmpty(apiDomain) || StringUtils.isEmpty(openId) || StringUtils.isEmpty(imei)){
            return ;
        }
        JSONObject json = new JSONObject();
        json.put("openid", openId);
        json.put("imei", imei);
        HttpReq.sendPostJson(apiDomain+"/getway/delete_relate_device", json.toString());
    }*/

}
